<template>
  <div class="sys-main-content">
    <div class="col-content">
      <div class="sys-search">
        <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="init()"
        >查询
        </el-button>
      </div>
      <div class="sys-table">
        <el-table
          :data="tableData"
        >
          <el-table-column
            label="用户名"
            prop="userName"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="用户状态"
            prop="status"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.status==0"
              >正常
              </el-tag>
              <el-tag
                v-if="scope.row.status==2"
                type="warning"
              >审核中
              </el-tag>
              <el-tag
                v-if="scope.row.status==1"
                type="danger"
              >冻结
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态开关" align="center">

            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status==2"
                icon="el-icon-check"
                type="text"
                @click="checkUser(scope.row)"
              >通过
              </el-button>
              <el-button
                v-if="scope.row.status==2"
                icon="el-icon-close"
                type="text"
                @click="removeUserById(scope.row.id)"
              >
                拒绝
              </el-button>

              <el-switch
                v-if="scope.row.status!=2"
                v-model="scope.row.status"
                :disabled="scope.row.status==2"
                :active-value="0"
                :inactive-value="1"
                @change="userUpdate(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column
            label="是否有主题"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag>{{ scope.row.themeId!=null?'是':'否' }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="创建时间"
            prop="createTime"
            align="center"
          ></el-table-column>
          <el-table-column
            label="修改时间"
            prop="updateTime"
            align="center"
          ></el-table-column>

          <el-table-column
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                @click="editUser(scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                size="mini"
                @click="removeUserById(scope.row.id)"
              >删除</el-button>
              <el-button type="text" size="mini" @click="updatePassword(scope.row)">密码修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="sys-pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next,total"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          label-position="right"
        >

          <el-form-item label="用户名" prop="userName">
            <el-input v-model="ruleForm.userName" />
          </el-form-item>

          <el-form-item label="用户状态">
            <el-tag :type="ruleForm.status==0?'':ruleForm.status==1?'danger':'warning'">
              {{ ruleForm.status==0?'正常':ruleForm.status==1?'冻结':'审核' }}
            </el-tag>
          </el-form-item>

          <el-form-item label="主题">
            <el-select v-model="ruleForm.themeId">
              <el-option v-for="(item,K) in themeList" :key="K" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像">
            <el-image
              style="width: 120px; height: 120px"
              fit="cover"
              :src="ruleForm.userHead"
            ></el-image>
            <el-upload
              ref="upload"
              class="upload-demo"
              :before-upload="beforeAvatarUpload"
              :action="uploadUrl + '&userId='+ruleForm.id"
              :on-preview="handlePreview"
              :on-success="submitSuccess"
              :on-error="submitError"
              :on-remove="handleRemove"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
            </el-upload>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <user-password-update v-if="UserPasswordUpdateVisible" ref="UserPasswordUpdate"></user-password-update>
  </div>
</template>

<script>
import { getUserList, removeUserById, updateUser } from '@/api/user'
import { getThemeSelectList } from '@/api/theme'
import { getTokenKey, getToken } from '@/utils/token'
import UserPasswordUpdate from './userPasswordUpdate'
export default {
  name: 'User',
  components: { UserPasswordUpdate },
  data() {
    return {
      UserPasswordUpdateVisible: false,
      uploadUrl: window.SITE_CONFIG.baseUrl + '/user/uploadUserHead?' + getTokenKey() + '=' + getToken(),
      fileList: [],
      dialogVisible: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      searchForm: {
        userName: ''
      },
      ruleForm: {
        id: '',
        userName: '',
        status: '',
        themeId: '',
        userHead: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ]
      },
      themeList: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    updatePassword(row) {
      this.UserPasswordUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.UserPasswordUpdate.init(row)
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
      return true
    },
    submitSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('上传成功')
        this.ruleForm.userHead = response.data
        this.init()
        this.handleClose()
      } else {
        this.$message.error('上传失败')
      }
    },
    submitError(err, file, fileList) {
      console.log(err)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateUser(
            {
              id: this.ruleForm.id,
              userName: this.ruleForm.userName,
              themeId: this.ruleForm.themeId
            }
          ).then(() => {
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.init()
          })
        } else {
          return false
        }
      })
    },
    editUser(row) {
      this.dialogVisible = true
      this.ruleForm = row
      // this.ruleForm.id = row.id
      // this.ruleForm.userName = row.userName
      // this.ruleForm.status = row.status
      // this.ruleForm.themeId = row.themeId
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 每页多少条
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val
    },
    init() {
      getUserList({
        current: this.currentPage,
        size: this.pageSize,
        userName: this.searchForm.userName
      }).then((r) => {
        this.tableData = r
      })
      getThemeSelectList().then((r) => {
        this.themeList = r
      })
    },
    removeUserById(id) {
      this.$confirm('确定删除当前用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeUserById(id).then((r) => {
          this.$message.success('操作成功')
          this.init()
        })
      })
    },
    checkUser(row) {
      this.$confirm('确定通过审核当前用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUser(
          {
            id: row.id,
            status: 0
          }
        ).then(() => {
          this.init()
          this.$message.success('审核通过')
        })
      }).catch(() => {
        this.init()
      })
    },
    userUpdate(row) {
      this.$confirm('确定修改当前用户状态吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUser(row).then(() => {
          this.init()
          this.$message.success('操作成功')
        })
      }).catch(() => {
        this.init()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  height: calc(100vh - 100px);
  .el-col {
    height: 100%;
  }
}
.col-content {
  height: calc(100vh - 100px)
}
</style>
